package com.meixiaoliang.portal.core.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import com.meixiaoliang.portal.modular.system.model.Attach;

public class FileUtil {

    /**
     * 文件 io 保存到 windows 服务器
     *
     * @param file                文件 io
     * @param baseDir       文件存储服务器根目录
     * @return
     * @throws IOException
     */
    public static String saveFile(MultipartFile file, String baseDir) throws IOException {
        LocalDate today = LocalDate.now();
        // 文件服务器路径,这里放文件名是为了查看方便,下载时文件名从数据库中获取
        String filePath = File.separator + today.getYear() + File.separator + today.getMonthValue() + File.separator + today.getDayOfMonth() + File.separator
                          + UuidUtil.generate() + File.separator + file.getOriginalFilename();
        // 文件全路径
        String truePath = baseDir + filePath;
        // 文件存储
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(truePath));
        return filePath;
    }

    /**
     * 文件下载
     *
     * @param response
     * @param attach   文件信息
     * @param baseDir  文件保存根目录
     */
    public static void download(HttpServletResponse response, Attach attach, String baseDir) {

        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) attach.getSize());

        OutputStream out = null;
        InputStream in = null;

        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(attach.getName().getBytes(StandardCharsets.UTF_8), "iso8859-1"));

            in = new BufferedInputStream(new FileInputStream(baseDir + attach.getPath()));
            // 需要浏览器输出流
            out = response.getOutputStream();
            int temp;
            while ((temp = in.read()) != -1) {
                out.write(temp);
            }
        } catch (IOException e) {

        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
            }
        }

    }

}